package com.pay.common;

import com.pay.common.domain.service.ValidateService;
import com.pay.common.enums.ResultCode;
import com.pay.common.exceptions.SystemException;
import com.pay.common.exceptions.UserNotExistException;
import com.pay.common.exceptions.ValidateException;
import com.pay.controller.Routes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.ui.Model;

/**
 *
 * @author Evan
 * @date 17/10/30
 */

@FunctionalInterface
public interface ProcessMVC<T> {
    Logger logger = LoggerFactory.getLogger(ProcessMVC.class);


    default String process(Model model, Routes routes) {

        ValidateService validate = new ValidateService();

        return process(model, validate, routes);
    }

    default String process(Model model, ValidateService validate, Routes routes) {

        JsonResult errorMsg = null;
        String view = Routes.LOGIN;

        try {
            model.addAttribute("routes", routes);
            view = this.service(model, view, validate);
        } catch (ValidateException ex) {
            errorMsg = JsonResult.renderMsg(ResultCode.PARAM_ERROR, getExcepMessage(ex));

            view = Routes.SYSTEM_ERROR;
        } catch (UserNotExistException ex) {
            errorMsg = JsonResult.renderMsg(ResultCode.USER_NOT_EXIST, getExcepMessage(ex));

            view = Routes.SYSTEM_ERROR;
        } catch (EmptyResultDataAccessException ex) {
            errorMsg = JsonResult.renderMsg(ResultCode.NO_DATA, getExcepMessage(ex));

            view = Routes.SYSTEM_ERROR;
        } catch (SystemException ex) {
            errorMsg = JsonResult.renderMsg(ResultCode.FAILED, getExcepMessage(ex));

            view = Routes.SYSTEM_ERROR;
        } catch (Exception ex) {
            errorMsg = JsonResult.renderMsg(ResultCode.FAILED, getExcepMessage(ex));
            logger.error(ResultCode.FAILED.getMsg(), ex);

            view = Routes.SYSTEM_ERROR;
        }

        if(errorMsg != null){
            model.addAttribute("errorMsg", errorMsg.getResult());
        }

        return view;
    }

    default String getExcepMessage(Exception ex) {
        return ex.toString()+" : "+ex.getMessage();
    }

    String service(Model model, String view, ValidateService validate);


}
